import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { CreateUserDto } from '../dto/user.dto';
import { Users } from '../entity/users.entity';
import { Roles } from 'src/entity/roles.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users)
    private readonly usersRepository: Repository<Users>,
    @InjectRepository(Roles)
    private readonly rolesRepository: Repository<Roles>,
  ) {}

  /** 新增用户实体 */
  async addUser(userDto: CreateUserDto): Promise<Users> {
    const user = new Users();
    const params = { ...user, ...userDto };
    return this.usersRepository.save(params);
  }

  /** 查找全部用户 */
  async queryUsers() {
    return this.usersRepository.find();
  }

  /** 通过 id 查找用户 */
  async getUserById(id: string) {
    return this.usersRepository.findOneBy({ id: id });
  }

  /** 删除用户 */
  async deleteUserById(id: string) {
    return this.usersRepository.delete(id);
  }

  /** 为用户分配角色 */
  async assignRolesToUser(userId: string, roleIds: string[]) {
    const user = await this.usersRepository.findOne({
      where: { id: userId },
      relations: ['roles'],
    });
    const roles = await this.rolesRepository.find({
      where: { id: In(roleIds) },
    });
    if (user && roles && roles.length) {
      user.roles = [...user.roles, ...roles];
      return this.usersRepository.save(user);
    }
  }
}
